<template>
	<basic-container>
		<avue-crud
			:option="option"
			:data="data"
			ref="crud"
			v-model="form"
			:table-loading="loading"
			:permission="permissionList"
			:page="page"
			@refresh-change="refreshChange"
			@search-change="searchChange"
			@search-reset="searchReset"
			@current-change="currentChange"
			@size-change="sizeChange"
			@selection-change="selectionChange"
			@on-load="onLoad"
		>
			<!--			<template slot="search">-->
			<!--				<div>-->
			<!--					<el-col :span="6">-->
			<!--						<el-form-item label="商品类型">-->
			<!--							<el-select v-model="goodsType" size="mini">-->
			<!--								<el-option key="普通商品" label="普通商品" value="1"></el-option>-->
			<!--								<el-option key="积分商品" label="积分商品" value="2"></el-option>-->
			<!--							</el-select>-->
			<!--						</el-form-item>-->
			<!--					</el-col>-->
			<!--					 &lt;!&ndash; <div style="width: 25%;margin-bottom: 8px;float: left;padding: 0 20px 0 10px;box-sizing: border-box;">-->
			<!--					      <el-form-item label="区域">-->
			<!--					        <el-cascader v-model="areaData"-->
			<!--					                     :options="chooseAreaOption"-->
			<!--					                     size="mini"-->
			<!--										 filterable-->
			<!--					                     @change="handleChange"></el-cascader>-->
			<!--					      </el-form-item>-->
			<!--					  </div> &ndash;&gt;-->
			<!--				</div>-->
			<!--				-->
			<!--			</template>-->
			<template slot="search">
				<el-col :span="6" style="margin-bottom: 9px;">
					<el-form-item label="商品分类">
						<el-cascader :props="classOptions" v-model="goodsClassId" :options="chooseProductOption" size="mini" @change="handleChange"></el-cascader>
					</el-form-item>
				</el-col>
			</template>
			<template slot="searchMenu">
				<el-button type="primary" size="mini" @click="outExcel()">导出</el-button>
				<el-button type="primary" size="mini" @click="outAllExcel()">完全导出</el-button>
			</template>
			<!-- 查看按钮  -->
			<template slot-scope="scope" slot="menu">
				<el-button icon="el-icon-view" type="text" size="small" @click="viewGoodsDetail(scope.row)">查看</el-button>
				<el-button v-if="scope.row.goodsStatus == 0" type="text" size="small" @click="unRulesDown(scope.row.id)" v-has="'/mall-cloud-base/goodsManage/shelves'">
					违规下架
				</el-button>
			</template>
			<template slot-scope="{ row }" slot="goodsMainPhotoUrl">
				<img :src="row.goodsMainPhotoUrl" style="width:50px;height:50px;" />
			</template>
			<template slot-scope="{ row }" slot="distributionAreaStr">
				<div style="cursor: pointer;" @click="handleRowClick(row)">点击查看</div>
			</template>
			<template slot-scope="{ row }" slot="goodsRecommend">
				<el-switch @change="rowSwitchChange(row)" v-model="row.goodsRecommend"></el-switch>
			</template>
			<!--<template slot="search">-->
			<!--<el-form-item label="商品分类">-->
			<!--<el-cascader v-model="productData"-->
			<!--:options="chooseProductOption"-->
			<!--size="mini"-->
			<!--@change="handleChange"></el-cascader>-->
			<!--</el-form-item>-->
			<!--</template>-->
		</avue-crud>
		<el-drawer title="商品详情" size="80%" :withHeader="false" :visible.sync="dialogTableVisible" width="80%">
			<add-goods v-if="dialogTableVisible" :isCheck="isCheck" :isPublish="false" :goodsId="goodsid"></add-goods>
		</el-drawer>
		<el-dialog title="区域" :visible.sync="currentGoodsVis" width="40%" center>
			<span style="padding: 20px;color: #000;">{{ currentGoodsName }}</span>
			<div style="padding: 20px;max-height: 300px;overflow: scroll;line-height: 30px;">
				<el-tree :data="currentAreas" :default-expanded-keys="[]" node-key="id" accordion ref="goodsClassTree" highlight-current :props="propsClass"></el-tree>
			</div>
		</el-dialog>
	</basic-container>
</template>
<script>
import { getGoodsSoRangeStr, getList, updateDisplay, getGoodsClassAll,getClassList, unRulesDown, showGoodsStock, editGoodsStock, listTree ,getOrganizationTreeNodeByIds } from '@/api/base/goods/goods';
import templateFreight from '@/components/goods/seller/templateFreight';
import checkItem from '@/components/goods/seller/checkItem';
import { mapGetters } from 'vuex';
import editor from '@/components/editor/richTextEditor';
import addGoods from '@/views/base/goods/seller/addGoods';
import { validatNum } from '@/util/validate';
import { getToken } from '@/util/store';
var Dict = JSON.parse(localStorage.getItem('mall-dictionary')).content;
var GOODS_STATUS = [];
var VAILD = [{
	label: '否',
	value: false
}, {
	label: '是',
	value: true
}, ]
Dict.GOODS_STATUS.forEach(item => {
	if (item.value != -3) {
		GOODS_STATUS.push(item);
	}
});
export default {
	data() {
		return {
			idList: [],
			propsClass: {
				label: 'name',
				id: 'id',
				children: 'childrenNodes',
			},
			classOptions: {
				label: 'className',
				value: 'id',
				children: 'childrenNodes',
			},
			currentGoodsName: '',
			currentAreas: '',
			currentGoodsVis: false,
			dialogVisibleSell: false, // 销量修改的对话框
			editData: {},
			goodsType: '1', //商品类型
			isCheck: false,
			dialogTableVisible: false,
			searchForm: {},
			form: {},
			query: {},
			loading: true,
			rolesTree: [],
			rolesKeys: [],
			box: false,
			stockVisible: false,
			skuId: '',
			goodsName: '',
			optionStock: {
				size: 'mini',
				addBtn: false,
				border: true,
				selection: false,
				editBtn: false,
				viewBtn: false,
				delBtn: false,
				searchBtn: false,
				refreshBtn: true,
				columnBtn: false,
				rowKey: 'skuId',
				// calcHeight: 380,80,
				dialogType: 'dialog',
				align: 'center',
				column: [
					{
						label: '商品名称',
						prop: 'goodsName'
					},
					{
						label: '规格',
						prop: 'skuName'
					},
					{
						label: '单价',
						prop: 'price'
					},
					{
						label: '库存',
						prop: 'stocks',
						type: 'number'
					},
					{
						label: '销量',
						prop: 'goodsSaleNum',
						type: 'number'
					}
				]
			},
			stockLoading: false,
			stockForm: {},
			stockData: [],
			page: {
				pageSize: 10,
				currentPage: 1,
				total: 0
			},
			chooseAreaOption: [],
			areaData: {},
			productData: [],
			option: {
				size: 'mini',
				excelBtn: false,
				editBtn: false,
				// delBtn: true,
				cancelBtn: false,
				addBtn: false,
				delBtn: false,
				//searchBtn: true,
				tip: true,
				border: true,
				index: false,
				selection: true,
				viewBtn: false,
				rowKey: 'id',
				height: 'auto',
				// calcHeight: 380,
				menuWidth: 200,
				searchMenuSpan: 12,
				column: [
					{
						label: '商品主图',
						prop: 'goodsMainPhotoUrl',
						fixed: true,
						slot: true,
						rules: [
							{
								required: true,
								message: '请输入主图片',
								trigger: 'blur'
							}
						]
					},
					{
						label: '商品名称',
						prop: 'goodsName',
						search: true,
						rules: [
							{
								required: true,
								message: '请输入商品名称',
								trigger: 'blur'
							}
						]
					},
					{
						label: '店铺名称',
						prop: 'storeName',
						search: true,
						rules: [
							{
								required: true,
								message: '请输入店铺名称',
								trigger: 'blur'
							}
						]
					},
					{
						label: '商品品牌',
						prop: 'goodsBrandId',
						search: true,
						type: 'select',
						searchFilterable:true,
						dicUrl: '/base/brand/listAll',
						props: {
							label: 'brandName',
							value: 'id'
						},
						rules: [
							{
								required: true,
								message: '请输入商品品牌',
								trigger: 'blur'
							}
						]
					},
					// {
					//   label: "发布人",
					//   prop: "userName",
					//   fixed: true,
					//   search: true,
					//   rules: [{
					//     required: true,
					//     message: "请输入发布人",
					//     trigger: "blur"
					//   }]
					// },
					{
						label: '商品价格',
						prop: 'showPrice',
						rules: [
							{
								required: true,
								message: '请输入商品价格',
								trigger: 'blur'
							}
						]
					},
					{
						label: '商品分类',
						prop: 'goodsClassId',
						// search: true,
						type: 'select',
						searchFilterable:true,
						dicUrl: 'base/goodsClass/listDicData?classLevel=2',
						props: {
							label: 'label',
							value: 'value'
						},
						rules: [
							{
								required: true,
								message: '请输入分类',
								trigger: 'blur'
							}
						]
					},
					{
						label: '商品状态',
						prop: 'goodsStatus',
						dicData: GOODS_STATUS,
						search: true,
						type: 'select'
					},
					//console端，页面展示的商品推荐是goodsRecommend
					{
						label: '商品推荐',
						prop: 'goodsRecommend',
						slot: true
					},
					{
						label: '商品ID',
						prop: 'id'
					},
					{
						label: '商品评分',
						prop: 'goodsAvgScore'
					},
					{
						label: '商品销量',
						prop: 'goodsSaleNum'
					},
					{
						label: '可见区域',
						prop: 'goodsSoRange',
						value: 'goodsSoRange',
						searchSpan: 6,
						search: true,
						defaultExpandAll: false,
						hide: true,
						dicUrl: '/base/organization/listTreeByUserOrganization',
						type: 'tree',
						props: {
							label: 'name',
							value: 'id',
							children: 'childrenNodes'
						}
					},
					{
						label: '区域',
						prop: 'distributionAreaStr',
						slot: true
					},
					{
						label: '是否为跨域商品',
						searchLabelWidth: 120,
						searchSpan: 8,
						search: true,
						dicData: VAILD,
						prop: 'isCrossBorderGood',
						type: 'select'
					}
				]
			},
			data: [],
			goodsid: '',
			chooseProductOption: [],
			goodsClassId:''
		};
	},
	watch: {
		'obj.inventoryType'() {
			if (this.obj.inventoryType == 'all') {
				this.optionView.group[2].column[1].display = false;
			} else {
				this.optionView.group[2].column[2].display = false;
				this.optionView.group[2].column[3].display = false;
				this.optionView.group[2].column[4].display = false;
				this.optionView.group[2].column[5].display = false;
				this.optionView.group[2].column[6].display = false;
			}
		},
		'obj.supplierId'() {
			if (this.obj.supplierId == '') {
				//自供货
				this.optionView.group[4].column[1].display = false;
				this.optionView.group[4].column[3].display = false;
				this.optionView.group[4].column[4].display = false;
				this.optionView.group[4].column[5].display = false;
			}
		},
		'obj.naturalPro'() {
			if (this.obj.naturalPro.length == 0) {
				this.optionView.group[1].column[0].display = false;
			}
		}
	},
	created() {
		// listTree().then(res => {
		//   if (res.data.code == 200) {
		//     console.log(res.data.data);
		//     this.chooseAreaOption = res.data.data;
		//     console.log(this.chooseAreaOption);
		//   }
		// });
		getClassList().then(res => {
			if (res.data.code == 200) {
				res.data.data.forEach(item=>{
					if(item.childrenNodes.length>0){
						item.childrenNodes.forEach(it=>{
							if(it.childrenNodes.length>0){
								it.childrenNodes.forEach(i=>{
									if(i.childrenNodes.length==0){
										delete i.childrenNodes
									}
								})
							}else{
								delete it.childrenNodes
							}
						})
					}else{
						delete item.childrenNodes
					}
				})
				this.chooseProductOption = res.data.data;
				console.log(this.chooseProductOption)
			}
		});
	},
	components: {
		editor,
		addGoods,
		templateFreight,
		checkItem
	},
	computed: {
		...mapGetters(['permission', 'userInfo']),
		permissionList() {
			return {};
		}
	},
	methods: {
		outExcel() {
			if (this.idList.length > 0){
				let token = getToken();
				let goodsName = this.query.goodsName === undefined ? '' : this.query.goodsName;
				let goodsBrandId = this.query.goodsBrandId === undefined ? '' : this.query.goodsBrandId;
				let goodsClassId = this.query.goodsClassId === undefined ? '' : this.query.goodsClassId;
				let goodsStatus = this.query.goodsStatus === undefined ? '' : this.query.goodsStatus;
				let count = this.query.count === undefined ? '' : this.query.count;
				let idList = this.idList;
				window.location.href =
						'/base/goodsManage/outExcel?token=' +
						token +
						'&goodsName=' +
						goodsName +
						'&goodsBrandId=' +
						goodsBrandId +
						'&goodsClassId=' +
						goodsClassId +
						'&goodsStatus=' +
						goodsStatus +
						'&count=' +
						count +
						'&idList=' +
						idList;
						setTimeout(()=>{
							this.idList = [];
							this.onLoad(this.page, this.query);
						},500)
			}
			else {
				this.$message({
					type: "error",
					message: "至少选择一笔数据"
				});
			}

		},
		outAllExcel(){
			this.idList = [];
			let token = getToken();
			let goodsName = this.query.goodsName === undefined ? '' : this.query.goodsName;
			let goodsBrandId = this.query.goodsBrandId === undefined ? '' : this.query.goodsBrandId;
			let goodsClassId = this.query.goodsClassId === undefined ? '' : this.query.goodsClassId;
			let goodsStatus = this.query.goodsStatus === undefined ? '' : this.query.goodsStatus;
			let count = this.query.count === undefined ? '' : this.query.count;
			window.location.href =
					'/base/goodsManage/outExcel?token=' +
					token +
					'&goodsName=' +
					goodsName +
					'&goodsBrandId=' +
					goodsBrandId +
					'&goodsClassId=' +
					goodsClassId +
					'&goodsStatus=' +
					goodsStatus +
					'&count=' +
					count;
		},
		//违规下架
		unRulesDown(id) {
			this.$confirm("确定下架该商品吗?", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning"
			})
			.then(() => {
				unRulesDown(id, -2).then(res => {
					if (res.status == 200 && res.data.code == 200) {
						this.$message.success('违规下架成功！');
						if (this.data.length == 1) {
							this.page.currentPage -= 1;
						}
						this.onLoad(this.page, this.query);
					} else {
						this.$message.error(res.data.message);
					}
				});
			})
			
		},
		closeDia() {
			this.dialogVisibleSell = false;
			this.editData = {};
			this.onStockLoad();
		},
		//编辑单条销量
		editStock(row) {
			this.editData = row;
			this.dialogVisibleSell = true;
			console.log(row);
		},
		refreshStockChange() {
			this.onStockLoad();
		},
		onStockLoad() {
			this.stockLoading = true;
			showGoodsStock(this.skuId).then(res => {
				if (res.status == 200 && res.data.code == 200) {
					res.data.data.forEach(item => {
						item.goodsName = this.goodsName;
					});
					this.stockData = res.data.data;
					this.stockLoading = false;
				} else {
					this.$message.error(res.data.message);
				}
			});
		},
		//弹框的取消
		closeDrawer() {
			this.onLoad(this.page);
		},
		// 销量修改
		editSell(row) {
			this.skuId = row.id;
			this.goodsName = row.goodsName;
			this.stockVisible = true;
			this.onStockLoad();
		},
		// 销量修改提交
		editSellSubmit() {
			if (!validatNum(this.editData.goodsSaleNum)) {
				this.$message.error('销量必须为正整数');
				return;
			}
			let data = {
				skuId: this.editData.skuId,
				goodsSaleNum: this.editData.goodsSaleNum
			};
			editGoodsStock(data).then(res => {
				if (res.status == 200 && res.data.code == 200) {
					this.$message.success(res.data.data);
					this.onLoad(this.page);
				} else {
					this.$message.error(res.data.message);
				}
			});
			this.dialogVisibleSell = false;
		},
		viewGoodsDetail(row) {
			console.log(row);
			this.goodsid = row.id;
			this.isCheck = true;
			this.dialogTableVisible = true;
			//  查看
		},
		//关闭
		cancelCheck() {
			this.dialogTableVisible = false;
		},
		handleRowClick(row) {
			this.currentGoodsName = '商品名称：' + row.goodsName;
			getOrganizationTreeNodeByIds(row.goodsSoRange).then(res => {
				if (res.data.code == 200) {
					this.currentAreas = res.data.data;
					this.currentGoodsVis = true;
				}
			});
		},
		searchReset() {
			this.query = {};
			// this.productData = [];
			this.goodsClassId=''
			this.onLoad(this.page);
		},
		searchChange(params, done) {
			this.page.currentPage = 1;
			this.query  = params;
			this.onLoad(this.page, params, done);
		},
		currentChange(currentPage) {
			this.page.currentPage = currentPage;
		},
		sizeChange(pageSize) {
			this.page.pageSize = pageSize;
		},
		//监控多选点击事件
		selectionChange(row) {
			let idList = []
			if (row.length > 0) {
				for (let item of row) {
					idList.push(item.id)
				}
				console.log(idList)
				this.idList = idList
			} else {
				this.idList = [];
			}
		},
		refreshChange() {
			this.onLoad(this.page);
		},
		onLoad(page, params = {}, done) {
			// debugger
			params.goodsType = this.goodsType;
			// if (this.productData != undefined && this.productData.length != 0) {
			// 	params.goodsClassId = this.productData[2];
			// }
			let tempParams = {};
			if (params.isCrossBorderGood) {
				tempParams.isCrossBorderGood = params.isCrossBorderGood;
			}
			if (params.goodsBrandId) {
				tempParams.goodsBrandId = params.goodsBrandId;
			}
			if (params.goodsClassId) {
				tempParams.goodsClassId = params.goodsClassId;
			}
			if (params.goodsName) {
				tempParams.goodsName = params.goodsName;
			}
			if (params.goodsSoRange) {
				tempParams.goodsSoRange = params.goodsSoRange;
			}
			if (params.goodsStatus == 0) {
				tempParams.goodsStatus = params.goodsStatus;
			} else {
				if (params.goodsStatus) {
					tempParams.goodsStatus = params.goodsStatus;
				}
			}
			let _query = {};
			if (this.query.isCrossBorderGood) {
				_query.isCrossBorderGood = this.query.isCrossBorderGood;
			}
			if (this.query.goodsBrandId) {
				_query.goodsBrandId = this.query.goodsBrandId;
			}
			if (this.query.goodsClassId) {
				_query.goodsClassId = this.query.goodsClassId;
			}
			if (this.query.goodsName) {
				_query.goodsName = this.query.goodsName;
			}
			if (this.query.goodsSoRange) {
				_query.goodsSoRange = this.query.goodsSoRange;
			}
			if (this.query.goodsStatus == 0) {
				_query.goodsStatus = this.query.goodsStatus;
			} else {
				if (this.query.goodsStatus) {
					_query.goodsStatus = this.query.goodsStatus;
				}
			}
			if (this.query.goodsType) {
				_query.goodsType = this.query.goodsType;
			}
			if (this.query.storeName) {
				_query.storeName = this.query.storeName;
			}
			tempParams.goodsType = params.goodsType;
			if (params.storeName) {
				tempParams.storeName = params.storeName;
			}
			// if(params.){}
			this.loading = true;
			getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
				if (done) {
					done();
				}

				this.loading = false;
				const data = res.data;
				data.data.forEach(item => {
					let arr = item.goodsSoRange.split(',');
					item.goodsSoRange = [];
					arr.forEach(area => {
						if (area) {
							item.goodsSoRange.push(Number(area));
						}
					});
				});
				this.page.total = data.count;
				this.data = data.data;
				if (this.query.goodsType == 2) {
					//积分商品
					this.option.column[3].label = '商品积分';
				} else {
					//普通商品
					this.option.column[3].label = '商品品牌';
				}
			});
		},
		rowSwitchChange(row) {
			if (row.goodsRecommend) {
				updateDisplay(row.id, 1);
			} else {
				updateDisplay(row.id, 0);
			}
		},
		handleChange(value) {
			this.query.goodsClassId=value[value.length-1]
			console.log(this.query)
			// this.onLoad(this.page);
		}
	}
};
</script>

<style></style>
